<?php

declare(strict_types=1);
/**
 * This file is part of MineAdmin.
 *
 * @link     https://www.mineadmin.com
 * @document https://doc.mineadmin.com
 * @contact  root@imoi.cn
 * @license  https://github.com/mineadmin/MineAdmin/blob/master/LICENSE
 */

namespace App\Repository\Course;

use App\Model\CourseTask;
use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Annotation\Transactional;
use Hyperf\Database\Model\Relations\Relation;

/**
 * Class CourseTaskRepository.
 * @extends IRepository<School>
 */
final class CourseTaskRepository extends IRepository
{
    public function __construct(protected readonly CourseTask $model) {}
    public function handleSearch(Builder $query, array $params): Builder
    {
        $with = array_merge(
            $params['with'] ?? [],
            ['creator', 'taskable', 'course', 'section', 'homeworks', 'lives']
        );

        return $query
            ->with($with)
            ->when(
                Arr::get($params, 'name'),
                static function (Builder $query, $name) {
                    $query->where('name', 'like', '%' . $name . '%');
                }
            )->when(
                Arr::get($params, 'course_id'),
                static function (Builder $query, $id) {
                    $query->whereCourseId($id);
                }
            )->when(
                Arr::get($params, 'section_id'),
                static function (Builder $query, $id) {
                    $query->whereSectionId($id);
                }
            );
    }
    public function handleItems(Collection $items): Collection
    {
        return $items->map(function ($item) {
            $item->extras = [
                'homeworks' => $item->homeworks->pluck('id') ?? [],
                'lives' => $item->lives->pluck('id') ?? [],
                'data' => $item->data,
                'video' => $item->video
            ];
            return $item;
        });
    }
    #[Transactional]
    public function create(array $data): mixed
    {
        $data['data'] = $data['extras']['data'] ?? [];
        $data['video'] = $data['extras']['video'] ?? [];
        $taskableModel = Relation::getMorphedModel($data['taskable_type']);
        $taskable = call_user_func([$taskableModel, 'create'], $data['taskable']);
        $data['taskable_id'] = $taskable->id;
        /**
         * @var CourseTask $model
         */
        $model = parent::create($data);

        $model->homeworks()->sync($data['extras']['homeworks'] ?? []);
        $model->lives()->sync($data['extras']['lives'] ?? []);

        return $model;
    }

    #[Transactional()]
    public function updateById(mixed $id, array $data): bool
    {
        $data['data'] = $data['extras']['data'] ?? [];
        $data['video'] = $data['extras']['video'] ?? [];
        $updated = parent::updateById($id, $data);
        /**
         * @var CourseTask
         */
        $model = $this->findById($id);
        $model->taskable()->update($data['taskable']);
        $model->homeworks()->sync($data['extras']['homeworks'] ?? []);
        $model->lives()->sync($data['extras']['lives'] ?? []);
        return $updated;
    }
}
